<template>
    <div class="container">
        <div class="mask"></div>
        <div class="wrap" ref="wrap">
            <div class="content"
                 element-loading-text="订阅器加载中..."
                 ref="content"
                 v-loading="loading">

                <div class="content-mask">

                </div>
                <div class="top">
                    <i class="icon el-icon-shopping"></i><span>订阅器</span>
                    <i @click="close" class="el-icon-close" title="关闭订阅器"></i>
                </div>
                <el-scrollbar :native="false" style="height: 100%;">

                    <div class="form-wrap">
                        <div class="item-wrap subscriber-name">
                            <div class="name">
                                订阅器名称：
                            </div>
                            <div class="condition">
                                <input type="text"
                                       :class="{'format-error':inputSubscribeNameError}"
                                       name="subscriber-name"
                                       autocomplete="off"
                                       placeholder="请输入订阅器名称"
                                       v-model="inputSubscribeName"
                                >
                                <span class="format-error-sign">订阅器名称不能为空</span>
                            </div>
                        </div>
                        <div class="item-wrap purchase">
                            <div class="name">
                                采购方式：
                            </div>
                            <div class="condition">
                                <el-select v-model="selectPurchase"
                                           filterable
                                           placeholder="请选择"
                                           value-key="id"
                                           @change="addPurchase"
                                           style="width: 260px;height: 35px;"
                                >
                                    <el-option
                                            v-for="item in purchaseOptions"
                                            :key="item.id"
                                            :label="item.name"
                                            :disabled="item.disabled"
                                            :value="item">
                                    </el-option>
                                </el-select>
<!--                                <i class="icon icon-plus" @click="addPurchase"></i>-->
                                <!--<button @click="addPurchase" class="add-condition">添加条件</button>-->
                                <span class="btn-keywords-item" v-for="(item,index) in purchaseList" :key="item.id">
                                    {{item.name}}
                                    <i @click="deletePurchase(index)"
                                       class="icon icon-delete-keywords el-icon-close">
                                    </i>
                                </span>
                            </div>
                        </div>
                        <div class="item-wrap announcement">
                            <div class="name">
                                公告类型：
                            </div>
                            <div class="condition">
                                <el-select v-model="selectAnnouncement"
                                           filterable
                                           placeholder="请选择"
                                           value-key="id"
                                           @change="addAnnouncement"
                                           style="width: 260px;height: 35px;"
                                >
                                    <el-option
                                            v-for="item in announcementOptions"
                                            :key="item.id"
                                            :label="item.name"
                                            :disabled="item.disabled"
                                            :value="item">
                                    </el-option>
                                </el-select>
<!--                                <i class="icon icon-plus" @click="addAnnouncement"></i>-->
                                <!--<button @click="addAnnouncement" class="add-condition">添加条件</button>-->

                                <span class="btn-keywords-item" v-for="(item,index) in announcementList" :key="item.id">
                                {{item.name}}
                                <i class="icon icon-delete-keywords el-icon-close"
                                   @click="deleteAnnouncement(index)"></i>
                            </span>
                            </div>
                        </div>
                        <div class="item-wrap keywords">
                            <div class="name">
                                关键词：
                            </div>
                            <div class="condition">
                                <input type="text"
                                       name="keywords"
                                       v-model="inputKeyword"
                                       @keyup.enter="addKeywords"
                                       placeholder="输入后按Enter添加"
                                       autocomplete="off">
<!--                                <i class="icon icon-plus" @click="addKeywords"></i>-->
                                <button @click="addKeywords" class="add-condition">添加条件</button>
                                <span :key="item" :title="item" class="btn-keywords-item"
                                      v-for="(item,index) in keywordsList">
                                    {{item.length>5?item.substr(0,5)+'...':item}} <i
                                        class="icon icon-delete-keywords el-icon-close"
                                        @click="deleteKeywords(index)"></i>
                                </span>
                            </div>
                        </div>
                        <div class="item-wrap select-region">
                            <div class="name">
                                选择地区：
                            </div>
                            <div class="condition">
                                <el-select v-model="selectProvince"
                                           filterable
                                           placeholder="省"
                                           style="width: 100px;height: 35px;"
                                           @change="provinceChange"
                                >
                                    <el-option
                                            v-for="item in provinceList"
                                            :key="item.key"
                                            :label="item.value"
                                            :disabled="item.disabled"
                                            :value="item.value">
                                    </el-option>
                                </el-select>
                                <el-select v-model="selectCity"
                                           filterable
                                           placeholder="市"
                                           @change="cityChange"
                                           style="width: 100px;height: 35px;margin-left: 10px;"
                                >
                                    <el-option
                                            v-for="item in cityList"
                                            :key="item.key"
                                            :label="item.value"
                                            :disabled="item.disabled"
                                            :value="item.value">
                                    </el-option>
                                </el-select>
<!--                                <i class="icon icon-plus" @click="addRegion"></i>-->
                                <!--<button @click="addRegion" class="add-condition">添加条件</button>-->
                                <span class="btn-keywords-item" v-for="(item,index) in regionList" :key="item.code">
                                    {{item.regionName}}
                                    <i class="icon icon-delete-keywords el-icon-close"
                                       @click="deleteRegion(index,item.regionLevel,item.code)">
                                    </i>
                                </span>
                            </div>
                        </div>
                        <div class="item-wrap item-money">
                            <div class="name">
                                项目金额：
                            </div>
                            <div class="condition">
                                <el-select v-model="selectMoney"
                                           filterable
                                           placeholder="请选择"
                                           @change="moneyChange"
                                           value-key="text"
                                           style="width: 260px;height: 35px;"
                                >
                                    <el-option
                                            v-for="item in moneyOptions"
                                            :key="item.text"
                                            :label="item.text"
                                            :value="item">
                                    </el-option>
                                </el-select>

                                <div class="custom-money" v-show="moneyCustomShow">
                                    <el-input-number v-model="moneyRange[0]"
                                                     :min="0"
                                                     :max="100000000"
                                                     style="margin-left: 10px;">
                                    </el-input-number>
                                    -
                                    <el-input-number v-model="moneyRange[1]"
                                                     :min="0"
                                                     :max="100000000">
                                    </el-input-number>
                                    <span>万元</span>
                                </div>

                            </div>
                        </div>
                        <div class="item-wrap send-message-type">
                            <div class="name">
                                接收频率：
                            </div>
                            <div class="condition">
                                <el-select v-model="selectSendType"
                                           filterable
                                           placeholder="请选择"
                                           style="width: 100px;height: 35px;"
                                >
                                    <el-option
                                            v-for="item in sendTypeList"
                                            :key="item.type"
                                            :label="item.name"
                                            :value="item.type">
                                    </el-option>
                                </el-select>
                                <el-select v-model="selectTime"
                                           filterable
                                           placeholder="请选择"
                                           v-if="selectSendType==0"
                                           style="width: 100px;height: 35px;margin-left: 10px;"
                                >
                                    <el-option
                                            v-for="item in timeList"
                                            :key="item.value"
                                            :label="item.text"
                                            :value="item.value">
                                    </el-option>
                                </el-select>
                                <template v-else>
                                    <el-select v-model="selectTimeSection[0]"
                                               filterable
                                               placeholder="请选择"
                                               style="width: 100px;height: 35px;margin-left: 10px;"
                                               @change="selectSectionChange('min')"
                                    >
                                        <el-option
                                            v-for="item in timeList"
                                            :key="item.value"
                                            :label="item.text"
                                            :value="item.value">
                                        </el-option>
                                    </el-select>
                                    <span style="margin-left: 10px;">至</span>
                                    <el-select v-model="selectTimeSection[1]"
                                               filterable
                                               placeholder="请选择"
                                               style="width: 100px;height: 35px;margin-left: 10px;"
                                               @change="selectSectionChange('max')"
                                    >
                                        <el-option
                                            v-for="item in timeList"
                                            :key="item.value"
                                            :label="item.text"
                                            :value="item.value">
                                        </el-option>
                                    </el-select>
                                </template>

                            </div>
                        </div>
                        <div class="item-wrap receive-method">
                            <div class="name">
                                接收方式：
                            </div>
                            <div class="condition">
                                <span v-for="(item,index) in receiveMethodList"
                                      :key="item.name"
                                      @click="chooseReceiveMethod(index,item.value)">
                                    <span class="checked-item"
                                          :class="{checked:chooseReceiveMethodIndex.includes(item.value),disabled:item.mustSelect}">
                                    </span>
                                    <span class="label">{{item.name}}</span>
                                </span>
                            </div>

                        </div>
                        <div class="item-wrap e-mail" v-show="chooseReceiveMethodIndex.includes(3)">
                            <div class="name">
                                推送微信：
                            </div>
                            <div class="condition">
                                <div class="wx-user-info" v-show="wxUserInfo.nickname">
                                    <img class="wx-header-img" v-if="wxUserInfo.headImgUrl" :src="wxUserInfo.headImgUrl" alt="微信头像">
                                    <span>{{wxUserInfo.nickname}}</span>
                                    <span class="unbundling" @click="unBinding">解绑</span>
                                </div>
                                <div class="binding" v-show="!wxUserInfo.nickname">
                                    <button v-if="!wxAuthorizationShow" @click="getBindingCode">获取授权</button>
                                    <button v-else @click="cancelBindingCode">取消操作</button>
                                    <div id="qrcode" v-show="wxAuthorizationShow"></div>
                                </div>
                            </div>

                        </div>
                        <div class="item-wrap e-mail" v-if="chooseReceiveMethodIndex.includes(1)">
                            <div class="name">
                                电子邮件：
                            </div>
                            <div class="condition">
                                <input type="text"
                                       name="e-mail"
                                       placeholder="请填写电子邮件地址"
                                       class="input-email"
                                       v-model="inputEmail"
                                       :class="{'format-error':inputEmailError}"
                                >
                                <span class="format-error-sign">
                                电子邮箱格式不正确
                            </span>
                            </div>

                        </div>
                        <div class="item-wrap phone-number" v-if="chooseReceiveMethodIndex.includes(2)">
                            <div class="name">
                                接收手机号：
                            </div>
                            <div class="condition">
                                <input type="text"
                                       name="phone-number"
                                       class="input-phone-number"
                                       placeholder="请填写接收短信的手机号"
                                       v-model="inputPhoneNumber"
                                       :class="{'format-error':inputPhoneNumberError}"
                                       disabled
                                >
                                <span class="format-error-sign">
                                手机号码格式不正确
                            </span>
                            </div>
                        </div>
                        <div class="item-wrap subscribe-duration" v-if="subscriberStatus!==2">
                            <div class="name">
                                {{subscriberStatus===4?'续费':'订阅'}}时长：
                            </div>
                            <div class="condition">
                                <div class="slider-wrap">
                                    <ul class="slider-item-list">
                                        <li class=""
                                            v-for="(item,index) in discountList"
                                            :key="item.id"
                                            :class="{active:index<=sliderValueIndex}"
                                            :style="{width:600/(discountList.length-1)+'px'}"
                                        >
                                            <div class="slider-stop" :class="{active:index<=sliderValueIndex}"
                                                 @click="changeSliderValue(index)">
                                                <div class="sign-text" :class="{active:index==sliderValueIndex}">
                                                    {{item.monthCount+'个月'}}
                                                </div>
                                                <div class="discount-text" v-if="item.discount<100"
                                                     :class="{active:index==sliderValueIndex}">
                                                    {{item.discount/10+'折'}}
                                                </div>
                                            </div>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="item-wrap subscribe-due-time" v-if="subscriberStatus!==1&&dueTime">
                            <div class="name">
                                到期时间：
                            </div>
                            <div class="condition">
                                <span>{{dueTime}}</span>
                                <button @click="changeSubscriberStatus(4)" class="btn-renew" v-if="subscriberStatus===2">续费</button>
                                <span class="sign-expire" v-if="subscriberStatus===2&&daysDue<=7">您的订阅即将过期，请及时续费！</span>
                                <span class="sign-expire" v-if="subscriberStatus===3">您的订阅已过期，请及时续费！</span>
                                <button @click="changeSubscriberStatus(2)" class="btn-cancel-renew" v-if="subscriberStatus===4">取消续费</button>
                            </div>
                        </div>
                    </div>
                </el-scrollbar>
                <div class="bottom">
                    <div class="bottom-box">
                        <div class="calc-total-fee" v-if="subscriberStatus!==2" v-show="computedSubscribeMoneyShow">
                            正在计算...
                        </div>
                        <div @click="goOrderDetail" class="btn-subscribe" v-if="subscriberStatus===1">
                            <i class="icon icon-dingyue"></i>
                            订阅
                        </div>
                        <div @click="saveSubscriber" class="btn-subscribe" v-if="subscriberStatus===2">
                            <i class="icon icon-dingyue"></i>
                            保存
                        </div>
                        <div @click="renew" class="btn-subscribe" v-if="subscriberStatus===3||subscriberStatus===4">
                            <i class="icon icon-dingyue"></i>
                            续费
                        </div>
                        <div class="total-fee" v-if="subscriberStatus!==2" v-show="!computedSubscribeMoneyShow">
                            ￥{{(subscribeRealMoney/100).toFixed(2)}}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <dialog-box
                v-if="closeSubscriberSign"
                confirm-text="关闭"
                confirm-text-color="gray"
                sign-text="将不再保存已修改的内容，是否关闭？"
                @closeDialogBox="closeDialogBox"
        >
        </dialog-box>
    </div>
</template>

<script>
    // import QRCode from 'qrcodejs2';
    export default {
        data() {
            let timeList = [];
            for (let i = 0; i < 24; i++) {
                timeList.push({
                    text: i + ':00',
                    value: i.toString()
                })
            }
            return {
                loading:true,
                closeSubscriberSign:false,
                id:0,
                subscriberStatus:1,//1、未创建/添加 2、已创建/修改 3、已过期 4.续费（未过期）
                inputSubscribeName: '',
                inputSubscribeNameError: false,
                selectPurchase: '',
                purchaseOptions: [
                    {
                        id:-1,
                        name:'全部'
                    }
                ],
                purchaseList: [],//选择的采购方式列表
                selectAnnouncement: '',
                announcementOptions: [
                    {
                        id:-1,
                        name:'全部'
                    }
                ],
                announcementList: [],//选择的公告类型列表

                inputKeyword: '',
                keywordsList: [],//添加的关键词列表
                selectProvince: '',
                selectProvinceCode: '',
                provinceList: [
                    {
                        key:'000000',
                        value:'全国'
                    }
                ],
                selectCity: '',
                selectCityCode: '',
                cityList: [],
                regionList: [],//选择/添加的地区列表
                selectMoney: '不限',
                moneyOptions: [
                    {
                        text: '不限',
                        range: [null, null]
                    },
                    {
                        text: '100万元以下',
                        range: [0, 100]
                    },
                    {
                        text: '100-500万元',
                        range: [100, 500]
                    },
                    {
                        text: '500-1000万元',
                        range: [500, 1000]
                    },
                    {
                        text: '1000-5000万元',
                        range: [1000, 5000]
                    },
                    {
                        text: '5000-1亿元',
                        range: [5000, 10000]
                    },
                    {
                        text: '1亿元以上',
                        range: [10000, null]
                    },
                    {
                        text: '自定义',
                        isCustom: true,
                        range: [1, 10000]
                    }
                ],
                moneyCustomShow: false,
                moneyRange: [null, null],
                selectSendType: 1,
                sendTypeList: [
                    {
                        name: '定时推送',
                        type: 0
                    },
                    {
                        name: '即时推送',
                        type: 1,
                    },
                ],
                selectTime: '9',//选择的时间
                selectTimeSection:['9','21'],
                timeList,//时间列表
                receiveMethodList: [
                    {
                        name: '消息中心（必选）',
                        value:0,
                        mustSelect: true,//是否为必选项
                    },
                    {
                        name: '微信公众号推送',
                        value:3
                    },
                    {
                        name: '电子邮件',
                        value:1
                    }
                ],
                chooseReceiveMethodIndex: [0, 1],
                inputEmail: '',
                inputEmailError: false,
                inputPhoneNumber: '',
                inputPhoneNumberError: false,
                discountList: [],
                sliderValueIndex: 1,
                subscribeOriginMoney: 0.00,
                subscribeRealMoney: 0.00,
                computedSubscribeMoneyShow: false,
                dueTime:'',//订阅截止时间
                daysDue:0,
                wxAuthorizationShow:false,//是否显示微信授权二维码
                authorizationResultTimer:null,
                wxUserInfo:{},
                wxPush:false
            }
        },

        watch: {
            wxPush(val){
                if(val){
                    if(!this.chooseReceiveMethodIndex.includes(3)){
                        this.chooseReceiveMethodIndex.push(3);
                    }
                }
            },
            inputSubscribeName(val) {
                this.inputSubscribeNameError = val === '';
            },
            inputEmail(val) {
                this.inputEmailError = !this.utils.testEmail(val);
            },
            inputPhoneNumber(val) {
                this.inputPhoneNumberError = !this.utils.testPhoneNumber(val);
                if (!this.inputPhoneNumberError) {
                    this.requestCommitSubscribe();
                }
            },
            sliderValueIndex() {
                this.requestCommitSubscribe();
            },
            selectSendType(val) {
                if (val === 0) {//定时推送
                    this.receiveMethodList.push({
                        name: '短信',
                        value:2
                    });
                } else {//即时推送
                    this.receiveMethodList = this.receiveMethodList.filter(item => {
                        return item.name !== '短信';
                    });
                    this.chooseReceiveMethodIndex = this.chooseReceiveMethodIndex.filter(item => {
                        return item !== 2;
                    });
                }
            },
            chooseReceiveMethodIndex(val){
                if(val.includes(2)){
                    this.inputPhoneNumber = this.$store.state.tel
                }else {
                    this.inputPhoneNumber = '';
                }
                this.wxPush = !!val.includes(3);
            }
        },
        mounted() {
            this.$request.searchConditionWithId().then(res => {
                console.log(res);
                if (res.status == 200) {
                    res.data.purchase.forEach(item => {
                        this.purchaseOptions.push({
                            id: item.key,
                            name: item.value,
                            disabled: false
                        });
                    });
                    res.data.announcements.forEach(item => {
                        this.announcementOptions.push({
                            id: item.key,
                            name: item.value,
                            disabled: false
                        });
                    });

                    this.$request.searchRegion({
                        level: 1
                    }).then(res => {
                        console.log(res);
                        if (res.status == 200) {
                            this.provinceList = this.provinceList.concat(res.data.filter(item => {
                                let regExp = new RegExp(/香港|澳门|台湾/);
                                return !regExp.test(item.value);
                            }));

                            this.$request.subscriberInfo().then(res=>{
                                this.loading = false;
                                if (res.status == 200) {
                                    console.log(res);
                                    let resData = res.data;
                                    if(resData){
                                        this.subscriberStatus = resData.isExpire?3:2;
                                        this.id = resData.id;
                                        this.inputSubscribeName = resData.name;
                                        this.dueTime = resData.dueTime;
                                        this.daysDue = resData.daysDue;
                                        if(resData.wxUserInfo){
                                            this.wxUserInfo = resData.wxUserInfo
                                        }
                                        this.wxPush = !!resData.wechatPush;
                                        if(resData.purchaseVO){
                                            if(resData.purchaseVO.length>0){
                                                resData.purchaseVO.forEach(item=>{
                                                    this.purchaseList.push({
                                                        id:item.key,
                                                        name:item.value
                                                    });
                                                    this.purchaseOptions.forEach(item2 => {
                                                        if (item.key == item2.id) {
                                                            item2.disabled = true;
                                                            this.purchaseOptions[0].disabled = true;
                                                        }
                                                    });
                                                });
                                            }else {
                                                this.purchaseList.push({
                                                    id:-1,
                                                    name:'全部'
                                                });
                                                this.purchaseOptions.forEach(item => {
                                                    item.disabled = true;
                                                });
                                            }

                                        }
                                        if(resData.announcementVO){
                                            if(resData.announcementVO.length>0){
                                                resData.announcementVO.forEach(item=>{
                                                    console.log(item)
                                                    this.announcementList.push({
                                                        id:item.key,
                                                        name:item.value
                                                    });
                                                    this.announcementOptions.forEach(item2 => {
                                                        if (item.key == item2.id) {
                                                            item2.disabled = true;
                                                            this.announcementOptions[0].disabled = true;
                                                        }
                                                    });
                                                });
                                            }else {
                                                this.announcementList.push({
                                                    id:-1,
                                                    name:'全部'
                                                });
                                                this.announcementOptions.forEach(item => {
                                                    item.disabled = true;
                                                });
                                            }

                                        }
                                        if(resData.keywordVO){
                                            resData.keywordVO.forEach(item=>{
                                                this.keywordsList.push(item.value)
                                            });
                                        }
                                        if(resData.regionNameVO){
                                            if(resData.regionNameVO.length>0){
                                                resData.regionNameVO.forEach(item=>{
                                                    this.regionList.push({
                                                        code:item.key,
                                                        regionName:item.value,
                                                        regionLevel:item.key.search('0000') === -1?2:1
                                                    });
                                                    this.provinceList.forEach(item2 => {
                                                        if (item.key == item2.key) {
                                                            item2.disabled = true;
                                                        }
                                                    });
                                                    this.provinceList[0].disabled = true;
                                                });
                                            }else {
                                                this.regionList.push({
                                                    code:"000000",
                                                    regionLevel:1,
                                                    regionName:"全国"
                                                })
                                                this.provinceList.forEach(item => {
                                                    item.disabled = true;
                                                });
                                            }

                                        }
                                        if(!resData.minMoney&&!resData.maxMoney){
                                            this.selectMoney = '不限'
                                        } else if (resData.minMoney&&!resData.maxMoney) {
                                            this.selectMoney = resData.minMoney/1000000+'万以上'
                                        } else if (!resData.minMoney&&resData.maxMoney) {
                                            this.selectMoney = resData.maxMoney/1000000+'万以下'
                                        }
                                        else {
                                            this.selectMoney = resData.minMoney/1000000+'-'+resData.maxMoney/1000000+'万';
                                        }
                                        this.moneyRange = [resData.minMoney/1000000,resData.maxMoney/1000000];

                                        this.selectSendType = resData.pushMode;
                                        this.selectTime = resData.pushMode==0?resData.pushHour:'9';
                                        this.selectTimeSection = resData.pushMode==1?resData.pushHour.split('-'):['9','21'];
                                        this.chooseReceiveMethodIndex = [0];
                                        resData.modeVO.forEach(item=>{
                                            if(item.modeValue){
                                                if(!this.chooseReceiveMethodIndex.includes(item.subscribeMode)){
                                                    this.chooseReceiveMethodIndex.push(item.subscribeMode);
                                                }
                                                if (item.subscribeMode==1){
                                                    this.inputEmail = item.modeValue;
                                                }
                                                if (item.subscribeMode==2){
                                                    this.inputPhoneNumber = item.modeValue;
                                                }
                                            }
                                        });
                                    }else {
                                        this.$request.queryMemberStatus().then(res => {
                                            console.log('获取会员到期时间',res);
                                            if (res.status == 200) {
                                                if(res.data){
                                                    if(!res.data.isExpire){
                                                        this.subscriberStatus = 2;
                                                        this.dueTime = res.data.dueTime;
                                                        this.daysDue = res.data.daysDue;
                                                    }else {
                                                        this.subscriberStatus = 3;
                                                    }
                                                }
                                            } else {
                                                this.requestError(res.status, res.message);
                                            }
                                        }, err => {
                                            console.log(err);
                                            this.requestFail(err);
                                        });
                                    }

                                } else {
                                    this.requestError(res.status, res.message);
                                }
                            },err => {
                                console.log(err);
                                this.requestFail(err);
                            });
                        } else {
                            this.requestError(res.status, res.message);
                        }
                    }, err => {
                        console.log(err);
                        this.requestFail(err);
                    });

                } else {
                    this.requestError(res.status, res.message)
                }
            }, err => {
                console.log(err);
                this.requestFail(err);
            });

            this.$request.discountList().then(res => {
                console.log(res);
                if (res.status == 200) {
                    this.discountList = res.data;
                    this.requestCommitSubscribe();
                } else {
                    this.requestError(res.status, res.message);
                }
            }, err => {
                console.log(err);
                this.requestFail(err);
            });
        },
        methods: {
            selectSectionChange(type){
                console.log(type);
                if(parseInt(this.selectTimeSection[0])<=parseInt(this.selectTimeSection[1])) return false;
                this.selectTimeSection.reverse();
            },
            startAuthorizationResultTimer(){
                this.authorizationResultTimer = setInterval(()=>{
                    this.$request.getBindingResult().then(res => {
                        console.log('获取用户微信授权结果',res);
                        if (res.status == 200) {
                            if(res.data){
                                console.log('用户微信授权成功');
                                this.wxUserInfo = res.data;
                                this.wxAuthorizationShow = false;
                                clearInterval(this.authorizationResultTimer);
                            }
                        } else {
                            this.requestError(res.status, res.message);
                        }
                    }, err => {
                        console.log(err);
                        this.requestFail(err);
                    });
                },2000);
            },
            getBindingCode(){
                this.wxAuthorizationShow = true;
                let QRCode = this.QRCode;
                if(this.qrcode){
                    this.startAuthorizationResultTimer();
                }else {
                    this.$request.getBindingCode().then(res => {
                        console.log('获取微信授权二维码',res);
                        if (res.status == 200) {
                            this.qrcode = new QRCode('qrcode', {
                                text: res.data,
                                width: 150,
                                height: 150,
                                colorDark : '#000000',
                                colorLight : '#ffffff',
                                correctLevel : QRCode.CorrectLevel.H
                            });
                            this.startAuthorizationResultTimer();
                        } else {
                            this.requestError(res.status, res.message);
                        }
                    }, err => {
                        console.log(err);
                        this.requestFail(err);
                    });
                }

            },
            cancelBindingCode(){
                this.wxAuthorizationShow = false;
                clearInterval(this.authorizationResultTimer);
            },
            unBinding(){
                this.$request.unBinging().then(res => {
                    console.log('解绑微信',res);
                    if (res.status == 200) {
                        this.wxUserInfo = {};
                        this.wxPush = false;
                    } else {
                        this.requestError(res.status, res.message);
                    }
                }, err => {
                    console.log(err);
                    this.requestFail(err);
                });
            },
            changeSubscriberStatus(status){
                this.subscriberStatus = status;
            },
            closeDialogBox(res){
                if(res.close){
                    console.log('点击关闭按钮');
                } else if(res.cancel){
                    console.log('点击取消');
                }else {
                    console.log('点击确定');
                    this.$store.commit('changeSubscriberShow', false);
                }
                this.closeSubscriberSign = false;
            },
            close() {
                this.closeSubscriberSign = true;
            },
            addPurchase() {
                if (!this.purchaseList.some(item => {
                    item.id === this.selectPurchase.id
                }) && this.selectPurchase !== '') {
                    this.purchaseList.push(this.selectPurchase);
                    this.purchaseOptions.forEach(item => {
                        if(this.selectPurchase.id===-1){
                            item.disabled = true;
                        }else if (item.id == this.selectPurchase.id) {
                            this.purchaseOptions[0].disabled = true;
                            item.disabled = true;
                        }
                    });
                    this.selectPurchase = '';
                }
            },
            deletePurchase(index) {
                this.purchaseOptions.forEach(item => {
                    if (this.purchaseList[index].id===-1||item.id == this.purchaseList[index].id) {
                        item.disabled = false;
                    }

                });
                this.purchaseList.splice(index, 1);
                if(this.purchaseList.length===0){
                    this.purchaseOptions[0].disabled = false;
                }
            },
            addAnnouncement() {
                if (!this.announcementList.some(item => {
                    item.id === this.selectAnnouncement.id
                }) && this.selectAnnouncement !== '') {
                    this.announcementList.push(this.selectAnnouncement);
                    this.announcementOptions.forEach(item => {
                        if(this.selectAnnouncement.id===-1){
                            item.disabled = true;
                        } else if (item.id == this.selectAnnouncement.id) {
                            this.announcementOptions[0].disabled = true;
                            item.disabled = true;
                        }

                    });
                    this.selectAnnouncement = '';
                }
            },
            deleteAnnouncement(index) {
                this.announcementOptions.forEach(item => {
                    if (this.announcementList[index].id===-1||item.id == this.announcementList[index].id) {
                        item.disabled = false;
                    }

                });
                this.announcementList.splice(index, 1);
                if(this.announcementList.length===0){
                    this.announcementOptions[0].disabled = false;
                }
            },
            addKeywords() {
                if (!this.keywordsList.includes(this.inputKeyword) && this.inputKeyword.trim() !== '') {
                    this.keywordsList.push(this.inputKeyword);
                    this.inputKeyword = '';
                }
            },
            deleteKeywords(index) {
                this.keywordsList.splice(index, 1);
            },
            provinceChange() {
                this.selectCity = '';
                this.provinceList.forEach(item => {
                    if (item.value === this.selectProvince) {
                        this.selectProvinceCode = item.key;
                    }
                });
                if(this.selectProvinceCode !== '000000'){
                    this.$request.searchRegion({
                        level: 2,
                        parentCode: this.selectProvinceCode
                    }).then(res => {
                        console.log(res);
                        if (res.status == 200) {
                            res.data.unshift({
                                key: this.selectProvinceCode,
                                value: '全部'
                            });
                            this.cityList = res.data;
                            this.cityList.forEach(item => {
                                this.regionList.forEach(item2 => {
                                    if (item.key == item2.code) {
                                        item.disabled = true;
                                    }
                                })
                            })
                        } else {
                            this.requestError(res.status, res.message);
                        }
                    }, err => {
                        console.log(err);
                        this.requestFail(err);
                    })
                }else{//选择全国
                    let newRegion = {
                        code: this.provinceList[0].code?this.provinceList[0].code:'000000',
                        regionName: this.provinceList[0].value,
                        regionLevel: 1,
                    };
                    this.provinceList.forEach(item => {
                        item.disabled = true;
                    });
                    this.selectProvince = '';
                    this.selectProvinceCode = '';
                    this.cityList = [];
                    this.selectCityCode = '';
                    this.selectCity = '';
                    this.selectCityCode = '';
                    this.regionList.push(newRegion);
                }

            },
            cityChange() {
                this.cityList.forEach(item => {
                    if (item.value === this.selectCity) {
                        this.selectCityCode = item.key;
                    }
                });
                this.addRegion();
            },
            addRegion() {
                if (this.selectCity) {
                    let newRegion = {};
                    if (this.selectCityCode.search('0000') === -1) {//选择地级市
                        newRegion = {
                            code: this.selectCityCode,
                            regionName: this.selectCity,
                            regionLevel: 2,
                            parentCode: this.selectProvinceCode
                        };
                        this.cityList.forEach(item => {
                            if (item.key.search('0000') !== -1 || item.key == this.selectCityCode) {
                                item.disabled = true;
                            }
                        });
                    } else {//选择全部
                        newRegion = {
                            code: this.selectProvinceCode,
                            regionName: this.selectProvince,
                            regionLevel: 1
                        };
                        this.provinceList.forEach(item => {
                            if (item.key == this.selectProvinceCode) {
                                item.disabled = true;
                            }
                        });
                        this.selectProvince = '';
                        this.selectProvinceCode = '';
                        this.cityList = [];
                        this.selectCityCode = '';
                    }

                    this.selectCity = '';
                    this.selectCityCode = '';
                    this.regionList.push(newRegion);
                    this.provinceList[0].disabled = true;
                }
            },
            deleteRegion(index, regionLevel, code) {
                // console.log(index,regionLevel,code)
                this.regionList.splice(index, 1);
                if (regionLevel == 1) {
                    if(code==='000000'){
                        this.provinceList.forEach(item => {
                            item.disabled = false;
                        })
                    }else {
                        this.provinceList.forEach(item => {
                            if (code == item.key) {
                                item.disabled = false;
                            }
                        })
                    }

                } else {
                    this.cityList.forEach(item => {
                        if (code == item.key) {
                            item.disabled = false;
                        }
                    });

                    let selectedCityList = this.cityList.filter(item => {
                        return item.disabled;
                    });
                    // console.log(selectedCityList);
                    if (selectedCityList.length <= 1&&this.cityList.length>0) {
                        this.cityList[0].disabled = false;
                    }
                }
                if(this.regionList.length===0){
                    // console.log(this.regionList.length)
                    this.provinceList[0].disabled = false;
                }
            },
            moneyChange(val) {
                // console.log(val);
                this.moneyRange = val.range;
                this.moneyCustomShow = val.isCustom;
            },

            chooseReceiveMethod(index,value) {
                if (this.chooseReceiveMethodIndex.includes(value)) {
                    this.chooseReceiveMethodIndex = this.chooseReceiveMethodIndex.filter(item => {
                        return this.receiveMethodList[index].mustSelect || item !== value;
                    });
                } else {
                    this.chooseReceiveMethodIndex.push(value);
                }
            },
            changeSliderValue(index) {
                this.sliderValueIndex = index;
            },
            requestSubmitSubscribeData(){
                let purchaseDictionarys = [];
                let announcemantDictionarys = [];
                let regions = [];
                this.purchaseList.forEach(item => {
                    if(item.id!==-1){
                        purchaseDictionarys.push({
                            id: item.id,
                            constantName: item.name,
                            constantType: 2
                        });
                    }
                });
                this.announcementList.forEach(item => {
                    if(item.id!==-1){
                        announcemantDictionarys.push({
                            id: item.id,
                            constantName: item.name,
                            constantType: 1
                        });
                    }

                });
                this.regionList.forEach(item => {
                    if(item.code!=='000000'){
                        regions.push(item.code);
                    }
                });
                return  {
                    name: this.inputSubscribeName,
                    announcemantDictionarys,
                    purchaseDictionarys,
                    regions,
                    keywords: this.keywordsList,
                    pushMode: this.selectSendType,
                    pushHour: this.selectSendType==0?this.selectTime:this.selectTimeSection[0]+'-'+this.selectTimeSection[1],
                    subscribeMode: this.chooseReceiveMethodIndex,
                    //tel: this.chooseReceiveMethodIndex.includes(2) && this.inputPhoneNumber ? this.inputPhoneNumber : null,
                    minMoney: this.moneyRange[0] * 100 * 10000,
                    maxMoney: this.moneyRange[1] ? this.moneyRange[1] * 100 * 10000 : null,
                    email: this.chooseReceiveMethodIndex.includes(1)?this.inputEmail:'',
                    originalMoney:this.subscribeOriginMoney,
                    realMoney:this.subscribeRealMoney,
                    wechatPush:this.wxPush?1:0
                };
            },
            requestCommitSubscribe() {//计算订阅器价格
                this.computedSubscribeMoneyShow = true;
                this.$request.computeSubscribePrice({
                    monthCount: this.discountList[this.sliderValueIndex].monthCount
                }).then(res => {
                    console.log(res);
                    if (res.status == 200) {
                        this.subscribeRealMoney = res.data.realMoney;
                        this.subscribeOriginMoney = res.data.originalMoney;
                        this.computedSubscribeMoneyShow = false;
                        // this.requestSubmitSubscribeData = res.data;
                    } else {
                        this.requestError(res.status, res.message);
                    }
                }, err => {
                    console.log(err);
                    this.requestFail(err);
                })

            },
            renew(){//续费
                this.saveSubscriber().then(()=>{
                    this.$request.renew({
                        monthCount:this.discountList[this.sliderValueIndex].monthCount
                    }).then(res=>{
                        if (res.status == 200) {
                            console.log('续费订阅器成功！');
                            this.$store.commit('changeSubscriberShow', false);
                            this.$router.push({
                                name: 'personal-order',
                                query: {
                                    orderId: res.data
                                }
                            })
                        } else {
                            this.requestError(res.status, res.message);
                        }
                    }, err => {
                        console.log(err);
                        this.requestFail(err);
                    });
                })
            },
            saveSubscriber(){
                return new Promise((resolve, reject)=>{
                    this.$request.editSubscribe({
                        id:this.id,
                        ...this.requestSubmitSubscribeData()
                    }).then(res=>{
                        if (res.status == 200) {
                            resolve(res);
                            this.$store.commit('changeSubscriberShow',false);
                        } else {
                            this.requestError(res.status, res.message);
                            reject();
                        }
                    }, err => {
                        console.log(err);
                        reject();
                        this.requestFail(err);
                    });
                });
            },
            goOrderDetail() {
                if (this.inputSubscribeName !== '' && !this.inputSubscribeNameError) {
                    if (this.purchaseList.length) {
                        if (this.announcementList.length) {
                            if (this.keywordsList.length) {
                                if (this.regionList.length) {
                                    console.log(123456)
                                    if (this.chooseReceiveMethodIndex.includes(1)) {
                                        if (this.inputEmail !== '' && !this.inputEmailError) {
                                            this.requestSubmitSubscribe();
                                        } else {
                                            this.inputEmailError = true;
                                        }
                                    }else {
                                        this.requestSubmitSubscribe();
                                    }
                                    /*if (this.chooseReceiveMethodIndex.includes(2)) {
                                        console.log(123);
                                        if (this.inputPhoneNumber !== '' && !this.inputPhoneNumberError) {
                                            this.requestSubmitSubscribe();
                                        } else {
                                            this.inputPhoneNumberError = true;
                                        }
                                    } else {
                                        this.requestSubmitSubscribe();
                                    }*/
                                } else {
                                    this.$alert('请至少添加一个 <span style="color:#F67B14">地区</span>', '警告', {
                                        dangerouslyUseHTMLString: true
                                    });
                                }
                            } else {
                                this.$alert('请至少添加一个 <span style="color:#F67B14">关键词</span>', '警告', {
                                    dangerouslyUseHTMLString: true
                                });
                            }
                        } else {
                            this.$alert('请至少添加一种 <span style="color:#F67B14">公告类型</span>', '警告', {
                                dangerouslyUseHTMLString: true
                            });
                        }
                    } else {
                        this.$alert('请至少添加一种 <span style="color:#F67B14">采购方式</span>', '警告', {
                            dangerouslyUseHTMLString: true
                        });
                    }
                } else {
                    this.inputSubscribeNameError = true;
                }
            },
            requestSubmitSubscribe() {
                let data = {
                    ...this.requestSubmitSubscribeData(),
                    monthCount: this.discountList[this.sliderValueIndex].monthCount
                };
                this.$request.submitSubscribe(data).then(res => {
                    console.log(res);
                    if (res.status == 200) {
                        console.log('提交订阅器成功！');
                        this.$store.commit('changeSubscriberShow', false);
                        this.$router.push({
                            name: 'personal-order',
                            query: {
                                orderId: res.data
                            }
                        })
                    } else {
                        this.requestError(res.status, res.message);
                    }
                }, err => {
                    console.log(err);
                    this.requestFail(err);
                })
            },
        }
    }
</script>

<style scoped lang="less">
    .container {
        .over-screen(fixed);
        z-index: 995;

        .mask {
            .over-screen(absolute, 50);
            z-index: 996;
        }

        .wrap {
            .size;
            .center(auto-x);
            position: absolute;
            top: 0;
            left: 0;
            .min-height(400px);
            padding: 50px 0;
            z-index: 997;

            .content {
                .width(811px);
                .height;
                background-color: #ffffff;
                .center(auto-x);
                .border-radius(4px);
                overflow: hidden;
                position: relative;

                .top {
                    .size(100%, 50px);
                    background-color: @main-color;
                    .center(text-x);
                    //.lh(50px);
                    .fz(23px);
                    .color(#ffffff);
                    position: absolute;
                    left: 0;
                    top: 0;
                    z-index: 999;

                    .el-icon-shopping {
                        .size(28px);
                        .bg('@{img-base-url}subscriber_icon-shopping.png');
                        vertical-align: middle;
                        margin-right: 15px;

                        & + span {
                            vertical-align: middle;
                        }
                    }
                    .el-icon-close{
                        .fr;
                        margin-top: 12px;
                        margin-right: 10px;
                        cursor: pointer;

                        &:hover{
                            transform: scale(1.2);
                            .transition(0.5s);
                        }
                    }
                }

                .form-wrap {
                    padding: 50px 0 70px;

                    .item-wrap {
                        .clearfix;
                        margin-top: 20px;
                        line-height: 40px;

                        i.icon-plus {
                            .size(14px, 14px);
                            .bg('@{img-base-url}subscriber_icon-add.png');
                            vertical-align: middle;
                            margin-left: 10px;
                            cursor: pointer;
                            .color(@main-color);
                        }
                        button.add-condition{
                            padding: 5px 10px;
                            background-color: @main-color;
                            .color(#ffffff);
                            .border-radius(2px);
                            font-family: AlibabaPuHuiTiR;
                            .fz(14px);
                            margin-left: 10px;
                        }

                        .btn-keywords-item {
                            display: inline-block;
                            padding: 7px 10px;
                            border: 1px solid @main-color;
                            .border-radius(4px);
                            vertical-align: middle;
                            .color(@main-color);
                            line-height: 1;
                            .fz(14px);
                            box-sizing: border-box;

                            &:nth-of-type(1) {
                                margin-left: 20px;
                            }

                            & + .btn-keywords-item {
                                margin-left: 10px;
                            }

                            .icon-delete-keywords {
                                .fz(10px);
                                font-weight: bold;
                                cursor: pointer;
                            }
                        }

                        .name {
                            .width(105px);
                            .fl;
                            .fz(14px);
                            .color(#7D7D7D);
                            //.lh(35px);
                            text-align: right;
                            padding: 0 15px 0 5px;
                        }

                        .condition {
                            .fl;
                            .max-width(680px);

                            .wx-user-info{
                                .wx-header-img{
                                    width: 35px;
                                    height: 35px;
                                    vertical-align: middle;
                                    margin-right: 10px;
                                }
                                .unbundling{
                                    color: @main-color;
                                    margin-left: 20px;
                                    cursor: pointer;

                                }
                            }

                            .binding{
                                position: relative;

                                #qrcode{
                                    width: 150px;
                                    height: 150px;
                                    border: 1px solid #0c0c0c;
                                    position: absolute;
                                    bottom: 30px;
                                    left: 70px;
                                }
                            }
                            input {
                                padding-left: 10px;
                            }

                            .custom-money {
                                display: inline-block;
                            }

                            .btn-renew{
                                margin-left: 10px;
                                .color(@main-color);
                            }
                            .sign-expire{
                                margin-left: 10px;
                                .color(@color-error);
                            }
                            .btn-cancel-renew{
                                margin-left: 10px;
                                .color(@color-disabled);
                            }
                        }

                        &.subscriber-name {
                            .condition {

                                input[name=subscriber-name] {
                                    .size(400px, 35px);
                                    .border-radius(4px);
                                    border: 1px solid #EBEBEB;
                                }
                            }
                        }

                        &.keywords {
                            .condition {

                                input[name=keywords] {
                                    .size(150px, 35px);
                                    .border-radius(4px);
                                    border: 1px solid #EBEBEB;
                                }
                            }
                        }
                        &.receive-method {
                            .condition {
                                margin-left: -20px;

                                & > span {
                                    cursor: pointer;

                                    .checked-item {
                                        display: inline-block;
                                        .size(11px, 11px);
                                        border: 1px solid #DBDBDB;
                                        vertical-align: middle;
                                        margin-left: 20px;

                                        &.checked {
                                            position: relative;

                                            &:after {
                                                display: inline-block;
                                                .size(11px, 9px);
                                                content: '';
                                                .bg('@{img-base-url}subscriber_icon-duigou.png', no-repeat, 2px bottom);
                                                position: absolute;
                                                left: 0;
                                                bottom: 1px;
                                            }

                                            &.disabled {
                                                background-color: #bbbbbb;

                                                &:after {
                                                    display: inline-block;
                                                    .size(11px, 8px);
                                                    content: '';
                                                    .bg('@{img-base-url}subscriber_icon-duigou-disabled.png');
                                                    position: absolute;
                                                    left: 0;
                                                    bottom: 1px;
                                                }
                                            }
                                        }
                                    }

                                    .label {
                                        .fz(14px);
                                        vertical-align: middle;
                                        margin-left: 3px;
                                    }
                                }
                            }
                        }

                        .input-style {
                            .size(260px, 35px);
                            border: 1px solid #EBEBEB;
                            .border-radius(4px);
                        }

                        &.e-mail {
                            .condition {
                                .input-email {
                                    .input-style;
                                }
                            }
                        }

                        &.phone-number {
                            .condition {
                                .input-phone-number {
                                    .input-style;
                                }
                            ;
                            }
                        }

                        &.subscribe-duration {
                            margin-bottom: 50px;

                            .condition {
                                @slider-wrap-width: 647px;
                                @slider-wrap-height: 12px;

                                .slider-wrap {
                                    display: inline-block;
                                    .size(@slider-wrap-width, @slider-wrap-height);
                                    background-color: #E7E7E7;
                                    .border-radius(6px);
                                    vertical-align: middle;

                                    ul.slider-item-list {
                                        .size;
                                        .clearfix;

                                        & > li {
                                            //.size(@slider-item-width);
                                            .height;
                                            .border-radius(@slider-wrap-height/2);
                                            .fl;
                                            position: relative;

                                            &:first-child {
                                                .width(47px) !important;
                                            }

                                            &.active {
                                                background-color: @main-color;
                                            }

                                            .slider-stop {
                                                @wh: 22px;
                                                .size(@wh, @wh);
                                                position: absolute;
                                                top: -(@wh - @slider-wrap-height)/2;
                                                right: -@wh/2;
                                                border: 2px solid #ffffff;
                                                .border-radius(50%);
                                                .box-shadow;
                                                .bg-linear-gradient(#dadada, #ebebeb, left);
                                                cursor: pointer;

                                                &.active {
                                                    background: @main-color !important;
                                                }

                                                z-index: 998;

                                                @text-width: 50px;

                                                .sign-text {
                                                    .width(@text-width);
                                                    .fz(14px);
                                                    .color(#7D7D7D);
                                                    .center(text-x);
                                                    position: absolute;
                                                    top: 16px;
                                                    left: 50%;
                                                    margin-left: -@text-width/2;

                                                    &.active {
                                                        .fz(16px);
                                                        .color(#333333);
                                                    }
                                                }

                                                .discount-text {
                                                    display: none;

                                                    &.active {
                                                        display: block;
                                                        .width(@text-width);
                                                        .fz(16px);
                                                        .center(text-x);
                                                        font-family: PingFang;
                                                        font-weight: 500;
                                                        position: absolute;
                                                        top: 38px;
                                                        left: 50%;
                                                        margin-left: -@text-width/2;
                                                        .color(@main-color);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                .bottom {

                    position: absolute;
                    left: 0;
                    bottom: 0;
                    z-index: 999;
                    background-color: #ffffff;

                    .bottom-box {
                        .size(800px, 50px);
                        border-top: 1px solid #EBEBEB;
                        margin-left: 11px;
                        .clearfix;
                        .fz(18px);
                        box-sizing: content-box;

                        & > div {
                            .fl;
                            .lh(50px);

                            &.calc-total-fee {
                                .color(@main-color);
                                margin-left: 20px;
                            }

                            &.total-fee {
                                .fr;
                                .color(@main-color);
                                margin-right: 59px;
                            }

                            &.btn-subscribe {
                                .fr;
                                .size(165px);
                                background-color: @main-color;
                                .color(#FFFFFF);
                                .center(text-x);
                                cursor: pointer;

                                i {
                                    display: inline-block;
                                    .size(15px, 17px);
                                    vertical-align: middle;
                                    .bg('@{img-base-url}subscriber_icon-dingyue.png');
                                }
                            }
                        }
                    }
                }
            }
        }
    }
</style>